<template>
  <div class="hotWord" id="hotWord">
    <!-- 功能按钮 -->
    <div class="hotWord_button">
      <a-button
        class="addButton"
        type="primary"
        :disabled="!btnPerm.includes('creatAble')"
        @click="addRecord"
      >
        <template #icon>
          <span class="iconfont icon-Add iconadd"></span>
        </template>
        新建分组
      </a-button>
    </div>
    <!-- 表格展示部分 -->
    <baseTable
      :columns="columns.hotWordColumns"
      :dataSource="configData.records"
      :isSelect="true"
      :scroll="scroll"
      ref="hotBaseTables"
      :isShowPagination="isShowPagination"
      :showCheckDelete="showCheckDelete"
      :total="configData.total"
      @deleteRecord="deleteSelectedAll"
      @changePage="changePage"
    >
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.ellipsis">
          <table-tool-tip :text="text" :column="column"></table-tool-tip>
        </template>
        <template v-if="column.dataIndex === 'oparation'">
          <a
            class="eidtRecords"
            :class="{ disable: !btnPerm.includes('hotWordDetailAble') }"
            @click="checkDetail(record)"
            >{{ record.oparation[0] }}</a
          >
          <a
            class="eidtRecords"
            :class="{ disable: !btnPerm.includes('editAble') }"
            @click="eidtRecord(record)"
            >{{ record.oparation[1] }}</a
          >
          <a-popconfirm
            placement="topRight"
            :disabled="!btnPerm.includes('deleteAble')"
            @confirm="confirmDelete(record)"
          >
            <template #title>
              <p style="width: 197px">删除此分组后，该分组下的所有热词将一并删除</p>
            </template>
            <a :class="{ disable: !btnPerm.includes('deleteAble') }">{{
              record.oparation[2]
            }}</a>
          </a-popconfirm>
        </template>
      </template>
      <template #otherOpration>
        <a-button
          :style="{ 'margin-left': '8px' }"
          @click="deleteSelectedAll"
          :disabled="!rowSelection.length || !btnPerm.includes('deleteAble')"
          >删除</a-button
        >
      </template>
    </baseTable>

    <!-- 新建热词模态框 -->
    <base-modal
      :width="modAlProps.width"
      :isVisible="isVisible"
      :title="modAlProps.title"
      :buttons="buttons"
      @handleOk="buttonMessage"
      @handleCancle="isVisible = false"
      class="sensitive_modal"
    >
      <template v-slot:body>
        <a-form
          name="advanced_search"
          autoComplete="off"
          class="hotward-form"
          :model="formState"
          ref="hotWordGroupFrom"
        >
          <template v-if="isAddOrEdit">
            <a-form-item
              :name="['hotWord', 'value']"
              :label="formState.hotWord.label"
              :rules="[formState.hotWord.rule]"
            >
              <a-input
                v-model:value="formState.hotWord.value"
                placeholder="不超过25个字"
                show-count
                :maxlength="25"
                allow-clear
              />
            </a-form-item>
            <a-form-item
              :name="['replaceWord', 'value']"
              :label="formState.replaceWord.label"
              :rules="[formState.replaceWord.rule]"
            >
              <base-tree
                :selectable="true"
                :defaultExpandAll="true"
                :checkStrictly="checkStrictly"
                :checkedKeys="checkedKeys"
                :treeData="treeData"
                @checked_Keys="checked_Keys"
                :fieldNames="fieldNames"
              ></base-tree>
            </a-form-item>
          </template>
          <template v-else>
            <a-form-item
              :name="['batchSensitiveWord', 'value']"
              :label="formState.batchSensitiveWord.label"
            >
              <upload
                :action="props_upload.action"
                :accept="props_upload.accept"
                :directory="props_upload.directory"
                :listType="props_upload.listType"
              >
              </upload>
            </a-form-item>
          </template>
        </a-form>
      </template>
    </base-modal>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, onMounted, nextTick, createVNode } from "vue";
import baseTable from "@/components/table/baseTable.vue";
import tableToolTip from "@/components/table/tableToolTip.vue";
import { useRouter } from "vue-router";
import columns from "@/components/table/tableConfig/columnsName";
import { getTableScroll } from "@/components/table/tableConfig/table";
import baseModal from "@/components/modal/baseModal.vue";
import msgModal from "@/components/modal/modelConfig/MsGModal";
import upload from "@/components/upload/uploadFile.vue";
import type { TreeProps } from "ant-design-vue";
import baseTree from "@/components/tree/baseTree.vue";
import { checkHotWord } from "./formRuler";
import { Modal, message } from "ant-design-vue";
import request from "@/api/index";
import { scrollType, modeProp } from "@/type.d";
import globalMethods from "@/utils/global";
import { routerPerm } from "@/utils/common";
// type
type configDataType = {
  total: number;
  size: number;
  records: any[];
};
interface dataSourceType {
  [propName: string]: any;
}
interface FormState {
  hotWord: dataSourceType;
  password: string;
  remember: boolean;
}

//data
const btnPerm = ref<any[]>([]);
const router = useRouter();
const treeData = ref();
let scroll: scrollType = reactive({ y: "", isFixed: false }); // 表单滚动设置 = ref<(string | number | any)[]>([]);
const checkedKeys = ref<(string | number | any)[]>([]);
const allKeys = ref<(string | number | any)[]>([]);
const checkStrictly = ref<Boolean>(true); //树型节点选择不关联
const isShowPagination = true; // 是否需要配分页器
const showCheckDelete = true; // 是否需要分页器中的自定义全选和删除
let datas = reactive<dataSourceType>({});

//树结构数据
const fieldNames = reactive<dataSourceType>({
  key: "id",
  title: "channelName",
});
//表格数据
let configData = reactive<configDataType>({ total: 0, size: 10, records: [] });
const hotBaseTables = ref<any>(null);
let rowSelection = ref<(string | number)[]>([]);
const deleteArr = ref<(string | number)[]>([]);
// 当前页和数量
const pageCurrent = ref<number>(1);
const pageSize = ref<number>(10);
// 模态框数据
const isAddOrEdit = ref<boolean>(true); //判断是新家、编辑或者批量上传来复用模态框
const isVisible = ref<boolean>(false);
const modAlProps: modeProp = reactive({
  width: "M",
  title: "新建热词分组",
});
const hotWordGroupFrom = ref<any>("hotWordGroupFrom");
const checkHotWordRange = (rule: any) => {
  if (!checkedKeys.value.length) {
    Promise.reject(rule.msg1);
  }
  return Promise.resolve();
};
const formState = reactive<dataSourceType>({
  hotWord: {
    value: "",
    rule: {
      required: true,
      validator: checkHotWord,
      trigger: ["blur"],
      msg1: "热词不可为空！",
      msg2: "热词已存在！",
      api: "fetchHotWordCategorysCateNameUnique",
      params: { id: "" },
    },
    label: "热词分组名",
  },
  replaceWord: {
    value: "",
    rule: {
      required: true,
      trigger: ["select"],
      msg1: "热词不可为空！",
      validator: checkHotWordRange,
    },
    label: "应用范围",
  },
  batchSensitiveWord: {
    //批量上传
    value: "",
    trigger: ["change", "blur"],
    rule: { required: true, message: "替换词不可为空！" },
    label: "上传文件:",
  },
  id: "",
  applyScope: 0,
});

//热词分组查看详情
const checkDetail = (record: any) => {
  if (!btnPerm.value.includes("hotWordDetailAble")) return;
  router.push({
    path: "/config/wordManages/hotWords/detail",
    query: {
      id: record.id,
      cateName: record.cateName,
    },
  });
};

// const checked_Keys = (obj: dataSourceType) => {
//   checkedKeys.value = obj.checkedKeys;
// };
// 选取站群
const checked_Keys = async (obj: dataSourceType) => {
  let isChecked = obj.e.checked;
  checkedKeys.value = obj.checkedKeys.checked;
  checkedKeys.value = [...new Set(checkedKeys.value)];
  if (obj.e.node.id == 0) {
    if (!obj.e.checked) {
      checkedKeys.value = [];
    }
  }
  nextTick(async () => {
    const loop = (data: dataSourceType) => {
      data.forEach((item: dataSourceType) => {
        if (!isChecked) {
          // if (checkedKeys.value.includes(item.id)) {
          //   for (let i = 0; i < checkedKeys.value.length; i++) {
          //     item.id == checkedKeys.value[i] ? checkedKeys.value.splice(i, 1) : "";
          //   }
          // }
        } else {
          !checkedKeys.value.includes(item.id) ? checkedKeys.value.push(item.id) : "";
        }
        if (item.children instanceof Array && item.children.length) {
          loop(item.children);
        }
      });
    };
    await loop(obj.e.node.children || []);
  });
};
// 模板文件上传配置
const props_upload = reactive<dataSourceType>({
  action: "",
  accept: "xlsx,xls",
  directory: false,
  listType: "text",
});
const buttons = ref<dataSourceType[]>([]); //模态框button按钮个数和文案修改

// computed
rowSelection = computed(() => {
  return hotBaseTables.value.selectedRowKeys;
});

//methods

const addRecord = async () => {
  //新加热词模态框条件修改
  //添加热词数据
  isVisible.value = true;
  isAddOrEdit.value = true;
  modAlProps.title = "新建热词分组";
  formState.hotWord.value = "";
  formState.hotWord.rule.params.id = "";
  checkedKeys.value = [];
  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
    {
      text: "保存并继续新建",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
  fetchHotWordCategorysChannelList();
  nextTick(() => {
    hotWordGroupFrom.value.resetFields();
  });
};
const eidtRecord = async (item: dataSourceType) => {
  if (!btnPerm.value.includes("editAble")) return;
  //编辑热词数据
  checkedKeys.value = [];
  fetchHotWordCategorysChannelList();
  isVisible.value = true;
  const data = await request.fetchHotWordCategorsDetail({ id: item.id });
  checkedKeys.value = [...new Set(data.channelIds)];
  console.log(checkedKeys.value,'checkedKeys.value')
  isAddOrEdit.value = true;
  modAlProps.title = "编辑热词分组";
  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
  ];

  nextTick(() => {
    hotWordGroupFrom.value.resetFields();
    formState.hotWord.value = data.cateName;
    formState.hotWord.rule.params.id = data.id;
    formState.id = data.id;
  });
};
// 新添或编辑热词调取接口
const buttonMessage = async (msg: dataSourceType) => {
  //保存
  const channelIds = checkedKeys.value.length
    ? checkedKeys.value.filter((item) => item > 0)
    : [];

  hotWordGroupFrom.value
    .validate()
    .then(() => {
      let params: dataSourceType = {
        applyScope: channelIds.length === allKeys.value.length ? 1 : 2,
        cateName: formState.hotWord.value,
        channelIds,
        id: formState.id,
      };
      let type: string = modAlProps.title.includes("编辑") ? "Edit" : "Add";

      request[type === "Edit" ? "fetcHotWordCategorysUpdate" : "fetchHotWordCategorys"](
        params
      )
        .then((res: any) => {
          if (res.code == "00000 00000") {
            getRdecord();
            formState.hotWord.value = "";
            formState.hotWord.rule.params.id = "";
            formState.id = "";
            checkedKeys.value = [];
            message.success(res.message);
          } else {
            message.error(res.message);
          }
        })
        .catch((err: any) => {
          throw new Error(err);
        });
      isVisible.value = msg.text == "保存" ? false : true;
    })
    .catch(() => {});
};
// 删除单个热词
const confirmDelete = async (item: any) => {
  deleteArr.value = [item.id];
  deleteRecords(deleteArr.value);
};
//删除已选所有热词
const deleteSelectedAll = async () => {
  let keys = rowSelection.value;
  Modal.confirm(
    Object.assign({}, msgModal.confirm, {
      title: "您确定删除选中的热词？删除后无法恢复",
      content: "删除分组后，分组下的所有的热词将一并删除",
      icon: createVNode("i", {
        class: "iconfont icon-warn warning_ICON",
      }),
      okText: "确定",
      onOk: async () => {
        await deleteRecords(keys);
        Modal.destroyAll();
      },
      onCancel() {
        Modal.destroyAll();
      },
    })
  );
};
const deleteRecords = async (keys: (string | number)[] = []) => {
  // 调接口删除热词
  await request.fetchHotWordCategorysDelete({ ids: keys }).then((res: any) => {
    if (res.code == "00000 00000") {
      hotBaseTables.value.selectedRowKeys = [];
      getRdecord();
      message.success(res.message);
    } else {
      message.error(res.message);
    }
  });
};

const getRdecord = async () => {
  // 获取热词分组表格数据
  const data: {} = {
    pageNumber: datas.pageNumber || pageCurrent.value,
    pageSize: datas.pageSize || pageSize.value,
    cateName: datas.cateName || "",
  };
  const telData = (await request.fetchHotWordCategorysPage(data)) || {};
  let reqData = telData;
  let sourceData = reactive({});
  const records: any[] = [];
  reqData?.records?.map((item: any, index: number) => {
    sourceData = {
      cateName: item.cateName,
      range: item.applyScope === 1 ? "所有栏目" : item.range ? item.range : "",
      oparation: ["查看详情", "编辑", "删除"],
      num: index + 1,
      createTime: item.createTime,
      id: item.id,
    };
    records.push(sourceData);
  });
  configData.total = reqData.total;
  configData.size = reqData.size;
  configData.records = records;
  nextTick(() => {
    scroll.y = getTableScroll(74, "hotWord").y;
    scroll.isFixed = getTableScroll(74, "hotWord").isFixed;
  });
};

//获取应用范围

const fetchHotWordCategorysChannelList = async () => {
  const data = await request.fetchHotWordCategorysChannelList();
  const treeList = data.length
    ? [
        {
          channelName: "全部栏目",
          children: data,
          id: 0,
        },
      ]
    : [];
  treeData.value = treeList;
  allKeys.value = getAllkey(data);
};

const getLoop = (arr: any[], keys: any[]) => {
  arr.length &&
    arr.map((item: any) => {
      keys.push(item.id);
      if (item.children && item.children.length) {
        getLoop(item.children, keys);
      }
    });
};

//获取全部的key
const getAllkey = (arr: any[]) => {
  const keys: any[] = [];
  getLoop(arr, keys);
  return keys;
};

//切换分页器
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  datas = {
    pageNumber: data.pageCurrent,
    pageSize: data.pageSize,
  };
  getRdecord();
  pageCurrent.value = data.pageCurrent;
  pageSize.value = data.pageSize;
};
//onmounted
onMounted(() => {
  btnPerm.value = routerPerm();
  console.log(btnPerm.value, "btnPerm.value");
  getRdecord();
  fetchHotWordCategorysChannelList();
});
defineExpose({
  checkedKeys,
});
</script>
<style lang="scss" scoped>
.hotWord {
  width: 100%;
  height: calc(100% - 72px);
  padding: 16px;
  background-color: #fff;

  .hotWord_button {
    padding-bottom: 24px;
    display: flex;

    .addButton {
      display: flex;
      align-items: center;
      margin-right: 8px;

      .iconadd {
        font-size: 24px;
        margin-right: 4px;
      }
    }

    .importButton {
      font-weight: 400;
      color: rgba(0, 0, 0, 0.85);
      margin-right: 8px;
    }

    .searchContent {
      margin-left: auto;
      margin-right: 0px;
    }
  }

  :deep(.ant-table-thead .ant-table-cell:nth-last-of-type(1)) {
    text-align: right;
    margin-right: 16px;
  }

  .eidtRecords {
    margin-right: 16px;
  }
}

::v-deep(.ant-tree) {
  padding-top: 4px;
}

:deep(.ant-form-item) {
  width: 604px;
  margin-bottom: 15px;
  display: flex;

  .ant-form-item-control {
    width: 494px;
    margin-left: 4px;
    flex: unset;
  }

  .ant-form-item-label {
    flex-grow: 0;
    width: 94px;
    text-align: right;
  }
}

.hotward-form {
  ::v-deep(.ant-form-item:last-child) {
    margin-bottom: 0;
  }
}

::v-deep(.ant-form-item-control-input-content:hover) {
  .anticon-close-circle {
    display: block;
  }

  .ant-input-show-count-suffix {
    // display: none;
  }
}

::v-deep(.ant-table-cell:nth-child(6)) {
  text-align: right;
}
</style>
